// pages/intention/notask/notask
let {
  getNoTask,
  editTime
} = require("../../../api/attract/select")
Page({
  /**
   * 页面的初始数据
   */
  data: {
    currentDate: new Date().getTime(),
    yw: 0,
    fangkStatus: 0,
    jhid: '',
    TimeShow: false,
    minDate: new Date().getTime(),
    Time: new Date().getTime(),
    navBtn: [{
      name: "7天内待访",
      id: "1"
    }, {
      name: "7-15天待访",
      id: "2"
    }, {
      name: "15-30天待访",
      id: "3"
    }, {
      name: "过期三天",
      id: "4"
    }],
    navNum: [{
      num: "0",
      id: "1"
    }, {
      num: "0",
      id: "2"
    }, {
      num: "0",
      id: "3"
    }, {
      num: "0",
      id: "4"
    }],
    // 月度待完善客户
    // 时间
    mouth_time: '',
    navNum3: [{
      num: "0",
      id: "1",
      name: "新增客户数",

    }, {
      num: "0",
      id: "2",
      name: "已完善信息数",

    }, {
      num: "0",
      id: "3",
      name: "资料完整度",

    }],
    navBtn2: [{
      name: "15-30天未联系",
      id: "1"
    }, {
      name: "30-60天未联系",
      id: "2"
    }, {
      name: "60-90天未联系",
      id: "3"
    }],
    navNum2: [{
      num: "0",
      id: "1"
    }, {
      num: "0",
      id: "2"
    }, {
      num: "0",
      id: "3"
    }],
    taskAll: {
      rw1: 0,
      rw2: 0,
      rw3: 0,
      rw4: 0
    },
    visitStatus: 1,
    record: [],
    tabType: 'month', // 默认月度
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    yearInlineList: [
      new Date().getFullYear() - 1,
      new Date().getFullYear(),
      new Date().getFullYear() + 1
    ],
    monthList: Array.from({length: 12}, (_, i) => i + 1), // 1~12月
  },
  checkFK(e) {
    let {
      index
    } = e.currentTarget.dataset
    console.log(index)
    this.setData({
      fangkStatus: index
    })
    this.getDateTask()
  },
  checkYW(e) {
    let {
      index
    } = e.currentTarget.dataset
    console.log(index)
    this.setData({
      yw: index
    })
    this.getDateTask()
  },
  inputOutTime(e) {
    this.setData({
      Time: e.detail,
    });
  },
  onConfirmOutTime() {
    editTime({
      jhid: this.data.jhid,
      time: this.formatTime(this.data.Time)
    }).then((res) => {
      wx.showToast({
        title: "调整日期成功",
        icon: "none",
      });
      this.onCloseOutTime();
      this.getDateTask()
    });
  },
  onCloseOutTime() {
    console.log(this.data.TimeShow)
    this.setData({
      TimeShow: !this.data.TimeShow
    })
  },
  goLook(e) {
    let {
      type,
      bid,
      jhid,
      tjsj,
      khbh,
      qymc
    } = e.currentTarget.dataset
    let bh_new = khbh.slice(0, 2)
    console.log(bid)
    wx.setStorageSync('qymclxr', qymc)
    switch (type) {
      case 'look':
        wx.navigateTo({
          url: `../specifics/specifics?bID=${bid}&id=1`,
        })
        break;
      case 'abandon':

        wx.showToast({
          title: "请至数据平台进行放弃",
          icon: "none",
        });

        break;
      case 'time':
        this.setData({
          jhid: jhid
        })
        console.log(jhid)
        this.onCloseOutTime()
        break;
      case 'dk':
        console.log(bh_new)
        if (bh_new == 'kh') {
          wx.navigateTo({
            url: `/pages/intention/follow/follow?bid=${bid}&affiliation=inner`,
          })
        } else if (bh_new == 'qd') {
          wx.navigateTo({
            url: `/pages/channel/follow/follow?bid=${bid}&affiliation=inner`,
          })
        }
        // wx.navigateTo({
        //   url: `../follow/follow?bid=bID=${bid}&affiliation=inner`,
        // })
        break;
      case 'bk':
        let gxsj = this.formatTime(tjsj, 2)
        console.log(gxsj)
        if (bh_new == 'kh') {
          wx.navigateTo({
            url: `/pages/intention/follow_dk/follow?bid=${bid}&affiliation=inner&tjsj=${gxsj}`,
          })
        } else if (bh_new == 'qd') {
          wx.navigateTo({
            url: `/pages/channel/follow_dk/follow?bid=${bid}&affiliation=inner&tjsj=${gxsj}`,
          })
        }

        break;
      default:
        break;
    }
  },
  formatTime(Time, type = 1) {
    // console.log(Time)
    let date = new Date(Time)
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hour = date.getHours().toString().padStart(2, '0');
    const minute = date.getMinutes().toString().padStart(2, '0');
    const second = date.getSeconds().toString().padStart(2, '0');
    if (type == 1) {
      return `${year}-${month}-${day}`;

    } else {
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    }

  },
  getDateTask() {
    let usesrInfo = wx.getStorageSync("userInfoMy");
    getNoTask(1, usesrInfo.jname, usesrInfo.bm).then(res => {
      this.setData({
        'taskAll.rw1': res.data[0].rw1,
        'taskAll.rw2': res.data[0].rw2,
        'taskAll.rw3': res.data[0].rw3,
        'taskAll.rw4': res.data[0].rw4,
      })
    })
    if (this.data.visitStatus == 1) {
      getNoTask(2, usesrInfo.jname, usesrInfo.bm).then(res => {
        res.data.forEach(item => {
          item.formatTime = this.formatTime(item.yxsj)
          item.formatTime2 = this.formatTime(item.yxsj, 2)

        })
        this.setData({
          record: res.data
        })
      })

    } else if (this.data.visitStatus == 2) {
      getNoTask(4, usesrInfo.jname, usesrInfo.bm).then(res => {
        res.data.forEach(item => {
          item.formatTime = this.formatTime(item.hfsj)
          item.yxra = Math.abs(item.yxr)
        })
        let resList1 = []
        let resList2 = []
        let resList3 = []
        let resList4 = []
        res.data.forEach(item => {
          if (item.yxr > 0 && item.yxr < 8) {
            resList1.push(item)
          } else if (item.yxr > 7 && item.yxr < 16) {
            resList2.push(item)
          } else if (item.yxr > 15 && item.yxr < 31) {
            resList3.push(item)
          } else if (item.yxr < 0) {
            resList4.push(item)
          }
        })

        if (this.data.fangkStatus == 1) {
          this.setData({
            record: resList1
          })
        } else if (this.data.fangkStatus == 2) {
          this.setData({
            record: resList2
          })
        } else if (this.data.fangkStatus == 3) {
          this.setData({
            record: resList3
          })
        } else if (this.data.fangkStatus == 4) {
          this.setData({
            record: resList4
          })
        } else {
          this.setData({
            record: res.data
          })
        }

      }).then(() => {
        getNoTask(3, usesrInfo.jname, usesrInfo.bm).then(res => {
          console.log('length', res.data.length)
          this.setData({
            'navBtn[0].name': "7天内待访",
            'navBtn[1].name': "7-15天待访",
            'navBtn[2].name': "15-30天待访",
            'navBtn[3].name': "过期三天",
            'navNum[0].num': res.data.length > 0 ? res.data[0].jh1 : 0,
            'navNum[1].num': res.data.length > 0 ? res.data[0].jh2 : 0,
            'navNum[2].num': res.data.length > 0 ? res.data[0].jh3 : 0,
            'navNum[3].num': res.data.length > 0 ? res.data[0].jh4 : 0,


          })
        })
      })

    } else if (this.data.visitStatus == 3) {
      getNoTask(6, usesrInfo.jname, usesrInfo.bm).then(res => {
        res.data.forEach(item => {
          item.formatTime = this.formatTime(item.hfsj)
        })
        this.setData({
          record: res.data
        })
      }).then(() => {
        getNoTask(5, usesrInfo.jname, usesrInfo.bm).then(res => {

          this.setData({
            'navNum[0].num': res.data[0].zsz ? res.data[0].zsz : 0,
            'navNum[1].num': res.data[0].zsbta ? res.data[0].zsbta : 0,
            'navNum[2].num': res.data[0].zsbtb ? res.data[0].zsbtb : 0,
            'navNum[3].num': res.data[0].wcl ? res.data[0].wcl + '%' : 0 + '%',
            'navBtn[0].name': "有效客户数",
            'navBtn[1].name': "待完善信息数",
            'navBtn[2].name': "已完善信息数",
            'navBtn[3].name': "资料完整度",
          })
        })

      })

    } else if (this.data.visitStatus == 4) {
      getNoTask(8, usesrInfo.jname, usesrInfo.bm, this.data.yw).then(res => {
        res.data.forEach(item => {
          item.formatTime = this.formatTime(item.yxsja)
        })
        this.setData({
          record: res.data
        })
      }).then(() => {
        getNoTask(7, usesrInfo.jname, usesrInfo.bm).then(res => {
          this.setData({
            'navNum2[0].num': res.data[0].lxa,
            'navNum2[1].num': res.data[0].lxb,
            'navNum2[2].num': res.data[0].lxc,
          })
        })
      })

    }
  },
  // 计算百分比
  calculatePercentage(numerator, denominator) {
    // 检查参数类型是否为数字
    if (typeof numerator !== 'number' || typeof denominator !== 'number') {
      return 'Error: Both arguments must be numbers';
    }

    // 检查分母是否为零
    if (denominator === 0) {
      return '0';
    }

    // 计算百分比
    const percentage = (numerator / denominator) * 100;

    // 格式化输出，保留两位小数并添加百分号
    return `${percentage}%`;
  },
  UserTap(e) {
    let {
      type
    } = e.currentTarget.dataset
    switch (type) {
      case '1':
        // 访客跟进
        break;
      case '2':
        // 完善跟进
        break;
      case '3':
        // 调整日期
        break;
      default:
        break;
    }
  },
  checkVisit(e) {
    console.log(e);
    let {
      status
    } = e.currentTarget.dataset;
    this.setData({
      visitStatus: status,
      fangkStatus: 0,
      yw: 0
    });
    this.getDateTask()
  },
  switchTab(e) {
    const type = e.currentTarget.dataset.type;
    let nowMonth = new Date().getMonth() + 1;
    this.setData({
      tabType: type,
      // 切换到月度时默认选中当月
      month: type === 'month' ? nowMonth : this.data.month
    });
    if (type === 'all') {
      this.getMonthOrAllData('all');
    } else {
      this.getMonthOrAllData('month');
    }
  },

  selectMonth(e) {
    const m = e.currentTarget.dataset.month;
    this.setData({
      month: m
    });
    this.getMonthOrAllData('month');
  },

  selectYear(e) {
    const y = e.currentTarget.dataset.year;
    this.setData({
      year: y
    });
    this.getMonthOrAllData('month');
  },

  selectPrevYear() {
    // 只有1月时允许切换上一年
    if (this.data.month == 1) {
      this.setData({
        year: this.data.year - 1,
        month: 12 // 切换到上一年时，月份变为12月
      });
      this.getMonthOrAllData('month');
    }
  },
  selectNextYear() {
    // 只有12月时允许切换下一年
    if (this.data.month == 12) {
      this.setData({
        year: this.data.year + 1,
        month: 1 // 切换到下一年时，月份变为1月
      });
      this.getMonthOrAllData('month');
    }
  },

  getMonthOrAllData(type) {
    let usesrInfo = wx.getStorageSync("userInfoMy");
    if (type === 'all') {
      getNoTask(5, usesrInfo.jname, usesrInfo.bm).then(res => {
        this.setData({
          'navNum[0].num': res.data[0].zsz ? res.data[0].zsz : 0,
          'navNum[1].num': res.data[0].zsbta ? res.data[0].zsbta : 0,
          'navNum[2].num': res.data[0].zsbtb ? res.data[0].zsbtb : 0,
          'navNum[3].num': res.data[0].wcl ? res.data[0].wcl + '%' : 0 + '%',
          'navBtn[0].name': "有效客户数",
          'navBtn[1].name': "待完善信息数",
          'navBtn[2].name': "已完善信息数",
          'navBtn[3].name': "资料完整度",
        })
      });
    } else {
      getNoTask(9, usesrInfo.jname, usesrInfo.bm, 0, this.data.year, this.data.month).then(res => {
        this.setData({
          
          'navNum3[0].num': res.data.length>0 ? res.data[0].zs : 0,
          'navNum3[1].num': res.data.length>0 ? res.data[0].zsa : 0,
          'navNum3[2].num': this.calculatePercentage(res.data.length>0 ? res.data[0].zsa : 0,res.data.length>0 ? res.data[0].zs : 0),
        })
      });
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    this.setData({
      visitStatus: options.id ? options.id : 1,
    });
    let usesrInfo = wx.getStorageSync("userInfoMy");
    getNoTask(1, usesrInfo.jname, usesrInfo.bm).then(res => {
      this.setData({
        'taskAll.rw1': res.data[0].rw1,
        'taskAll.rw2': res.data[0].rw2,
        'taskAll.rw3': res.data[0].rw3,
        'taskAll.rw4': res.data[0].rw4,
      })
    })
    const nowMonth = new Date().getMonth() + 1;
    const nowYear = new Date().getFullYear();
    this.setData({
      tabType: 'month',
      year: nowYear,
      month: nowMonth,
    });
    this.getMonthOrAllData('month');
    this.getDateTask()

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.onLoad()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});